// 统计功能模块
class StatsManager {
    constructor() {
        this.stats = {
            totalPhotos: 0,
            groupCount: 0,
            today: 0,
            week: 0,
            month: 0,
            trendData: [],
            rankingData: [],
            distributionData: []
        };
        console.log('StatsManager 构造函数被调用');
    }

    // 初始化统计
    async init() {
        console.log('=== 统计模块初始化开始 ===');
        try {
            await this.calculateStats();
            this.renderStats();
            console.log('=== 统计模块初始化完成 ===');
        } catch (error) {
            console.error('统计模块初始化失败:', error);
        }
    }

    // 计算统计数据
    async calculateStats() {
        console.log('=== 计算统计数据 ===');
        
        // 获取照片数据
        const photos = this.getPhotosData();
        console.log('获取到照片数据:', photos.length, '张');
        
        // 计算基础统计
        this.stats.totalPhotos = photos.length;
        this.stats.groupCount = this.calculateGroupCount(photos);
        
        // 计算时间统计
        this.calculateTimeStats(photos);
        
        // 计算趋势数据
        this.calculateTrendData(photos);
        
        // 计算排行榜
        this.calculateRankingData(photos);
        
        // 计算分布数据
        this.calculateDistributionData(photos);
        
        console.log('统计数据计算完成:', this.stats);
    }

    // 获取照片数据
    getPhotosData() {
        if (typeof gallery !== 'undefined' && gallery.photos) {
            return gallery.photos;
        }
        return [];
    }

    // 计算分组数量
    calculateGroupCount(photos) {
        const groups = new Set();
        photos.forEach(photo => {
            if (photo.group && photo.group !== '未分组') {
                groups.add(photo.group);
            }
        });
        return groups.size;
    }

    // 计算时间统计
    calculateTimeStats(photos) {
        const now = new Date();
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        const weekStart = new Date(today.getTime() - (today.getDay() * 24 * 60 * 60 * 1000));
        const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
        
        this.stats.today = 0;
        this.stats.week = 0;
        this.stats.month = 0;
        
        photos.forEach(photo => {
            const photoDate = new Date(photo.timestamp);
            
            if (photoDate >= today) {
                this.stats.today++;
            }
            
            if (photoDate >= weekStart) {
                this.stats.week++;
            }
            
            if (photoDate >= monthStart) {
                this.stats.month++;
            }
        });
        
        console.log('时间统计:', {
            '今日': this.stats.today,
            '本周': this.stats.week,
            '本月': this.stats.month
        });
    }

    // 计算趋势数据
    calculateTrendData(photos) {
        const trendData = [];
        const now = new Date();
        
        // 生成最近7天的数据
        for (let i = 6; i >= 0; i--) {
            const date = new Date(now.getTime() - (i * 24 * 60 * 60 * 1000));
            const dayStart = new Date(date.getFullYear(), date.getMonth(), date.getDate());
            const dayEnd = new Date(dayStart.getTime() + 24 * 60 * 60 * 1000);
            
            const count = photos.filter(photo => {
                const photoDate = new Date(photo.timestamp);
                return photoDate >= dayStart && photoDate < dayEnd;
            }).length;
            
            trendData.push({
                date: date,
                count: count,
                label: this.formatDateLabel(date)
            });
        }
        
        this.stats.trendData = trendData;
        console.log('趋势数据:', trendData);
    }

    // 计算排行榜数据
    calculateRankingData(photos) {
        const groupCounts = {};
        
        photos.forEach(photo => {
            if (photo.group && photo.group !== '未分组') {
                groupCounts[photo.group] = (groupCounts[photo.group] || 0) + 1;
            }
        });
        
        const ranking = Object.entries(groupCounts)
            .map(([group, count]) => ({ group, count }))
            .sort((a, b) => b.count - a.count)
            .slice(0, 5); // 取前5名
        
        this.stats.rankingData = ranking;
        console.log('排行榜数据:', ranking);
    }

    // 计算分布数据
    calculateDistributionData(photos) {
        const groupCounts = {};
        
        photos.forEach(photo => {
            if (photo.group && photo.group !== '未分组') {
                groupCounts[photo.group] = (groupCounts[photo.group] || 0) + 1;
            }
        });
        
        const total = Object.values(groupCounts).reduce((sum, count) => sum + count, 0);
        
        const distribution = Object.entries(groupCounts)
            .map(([group, count]) => ({
                group,
                count,
                percentage: total > 0 ? Math.round((count / total) * 100) : 0
            }))
            .sort((a, b) => b.count - a.count);
        
        this.stats.distributionData = distribution;
        console.log('分布数据:', distribution);
    }

    // 格式化日期标签
    formatDateLabel(date) {
        const today = new Date();
        const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
        
        if (date.toDateString() === today.toDateString()) {
            return '今天';
        } else if (date.toDateString() === yesterday.toDateString()) {
            return '昨天';
        } else {
            return `${date.getMonth() + 1}/${date.getDate()}`;
        }
    }

    // 渲染统计数据
    renderStats() {
        console.log('=== 渲染统计数据 ===');
        
        this.renderOverviewStats();
        this.renderTimeStats();
        this.renderTrendChart();
        this.renderRankingList();
        this.renderDistributionList();
        
        console.log('统计数据渲染完成');
    }

    // 渲染概览统计
    renderOverviewStats() {
        const totalPhotosElement = document.getElementById('stats-total-photos');
        const groupCountElement = document.getElementById('stats-group-count');
        
        if (totalPhotosElement) {
            totalPhotosElement.textContent = this.stats.totalPhotos;
        }
        
        if (groupCountElement) {
            groupCountElement.textContent = this.stats.groupCount;
        }
    }

    // 渲染时间统计
    renderTimeStats() {
        const todayElement = document.getElementById('stats-today');
        const weekElement = document.getElementById('stats-week');
        const monthElement = document.getElementById('stats-month');
        
        if (todayElement) {
            todayElement.textContent = this.stats.today;
        }
        
        if (weekElement) {
            weekElement.textContent = this.stats.week;
        }
        
        if (monthElement) {
            monthElement.textContent = this.stats.month;
        }
    }

    // 渲染趋势图
    renderTrendChart() {
        const trendChartElement = document.getElementById('trend-chart');
        if (!trendChartElement) return;
        
        const maxCount = Math.max(...this.stats.trendData.map(item => item.count), 1);
        
        const chartHTML = this.stats.trendData.map(item => {
            const height = maxCount > 0 ? (item.count / maxCount) * 80 : 0;
            return `
                <div class="trend-bar" style="height: ${height}px;">
                    <div class="trend-value">${item.count}</div>
                    <div class="trend-label">${item.label}</div>
                </div>
            `;
        }).join('');
        
        trendChartElement.innerHTML = chartHTML;
    }

    // 渲染排行榜
    renderRankingList() {
        const rankingListElement = document.getElementById('ranking-list');
        if (!rankingListElement) return;
        
        if (this.stats.rankingData.length === 0) {
            rankingListElement.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">暂无数据</div>';
            return;
        }
        
        const rankingHTML = this.stats.rankingData.map((item, index) => {
            const rankClass = index < 3 ? `rank-${index + 1}` : '';
            return `
                <div class="ranking-item">
                    <div class="ranking-info">
                        <div class="ranking-number ${rankClass}">${index + 1}</div>
                        <div class="ranking-name">${item.group}</div>
                    </div>
                    <div class="ranking-count">${item.count}张</div>
                </div>
            `;
        }).join('');
        
        rankingListElement.innerHTML = rankingHTML;
    }

    // 渲染分布列表
    renderDistributionList() {
        const distributionListElement = document.getElementById('distribution-list');
        if (!distributionListElement) return;
        
        if (this.stats.distributionData.length === 0) {
            distributionListElement.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">暂无数据</div>';
            return;
        }
        
        const distributionHTML = this.stats.distributionData.map(item => {
            return `
                <div class="distribution-item">
                    <div class="distribution-info">
                        <div class="distribution-icon">📁</div>
                        <div class="distribution-name">${item.group}</div>
                    </div>
                    <div class="distribution-bar">
                        <div class="distribution-fill" style="width: ${item.percentage}%"></div>
                    </div>
                    <div class="distribution-count">${item.count}</div>
                </div>
            `;
        }).join('');
        
        distributionListElement.innerHTML = distributionHTML;
    }

    // 刷新统计
    async refresh() {
        console.log('=== 刷新统计数据 ===');
        await this.calculateStats();
        this.renderStats();
        console.log('统计数据刷新完成');
    }
}

// 创建全局统计实例
console.log('创建全局统计实例');
const statsManager = new StatsManager();

// 页面加载完成后初始化统计
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，初始化统计模块');
    statsManager.init();
});

// 导出全局函数供HTML调用
console.log('导出全局统计函数');
window.refreshStats = () => {
    console.log('=== 调用全局refreshStats函数 ===');
    if (typeof statsManager !== 'undefined') {
        statsManager.refresh();
    } else {
        console.error('statsManager对象不存在！');
    }
}; 